﻿/* 
arunes.crmjslib v1.0.0 
last update: 2012-05-10 10:17
*/

// class and constructor
function arunesCrmJsLib() {

    // if content in iframe
    if (Xrm.Page.getAttribute == undefined)
        Xrm = parent.Xrm;

    // get elm. value
    this.getValue = function (elmId) { return Xrm.Page.getAttribute(elmId).getValue(); }

    // get current form's guid
    this.getCurrentId = function () { return Xrm.Page.data.entity.getId(); }

    // get elm. text (for picklists, lookups)
    this.getText = function (elmId) {
        var obj = Xrm.Page.ui.controls.get(elmId);
        if (obj != null) {
            switch (obj.getControlType()) {
                case 'lookup':
                    var val = this.getValue(elmId);
                    if (val != null) return val[0].name;
                    break;
                case 'optionset': return Xrm.Page.getAttribute(elmId).getText();
            }
        }
        return null;
    }

    // set elm. value
    this.setValue = function (elmId, val) { Xrm.Page.getAttribute(elmId).setValue(val); }

    // set lookup value
    this.setLookupValue = function (elmId, id, name, type) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = type;
        this.setValue(elmId, lookupValue);
    }

    // set elm. disable
    this.setDisabled = function (elmId, disable) { Xrm.Page.ui.controls.get(elmId).setDisabled(disable); }

    // set elm. visibility
    this.setVisible = function (elmId, visible) { Xrm.Page.ui.controls.get(elmId).setVisible(visible); }

    // set tab/section visibility
    this.setVisibleTabSection = function (tabname, sectionname, show) {
        var tab = Xrm.Page.ui.tabs.get(tabname);
        if (tab != null) {
            if (sectionname == null)
                tab.setVisible(show);
            else {
                var section = tab.sections.get(sectionname);
                if (section != null) {
                    section.setVisible(show);
                    if (show) tab.setVisible(show);
                }
            }
        }
    }

    // get crm form type (0:Undefined, 1:Create, 2:Update, 3:Read Only, 4:Disabled, 5:Quick Create (Deprecated), 6:Bulk Edit)
    this.getFormType = function () { return Xrm.Page.ui.getFormType(); }

    // set focus on element
    this.setFocus = function (elmId) { Xrm.Page.ui.controls.get(elmId).setFocus(); }

    // get server url
    this.getServerUrl = function () {
        try {
            var url = document.location.toString();
            var curHost = url.split('//')[1].split('/')[0]; //crm2011dev
            var crmHost = WEB_SERVER_HOST; // crm2011dev
            var organization = ORG_UNIQUE_NAME; // orgname
            var protocol = url.split('//')[0]; // http
            var isOnPremise = AUTHENTICATION_TYPE == 0; // true

            if (isOnPremise)
                return protocol + "//" + curHost + "/" + organization;
            else
                return protocol + "//" + curHost;
        }
        catch (Error) {
            return Xrm.Page.context.getServerUrl(); // default dönsün
        }
    }

    // get service url
    this.getServiceUrl = function () { return this.getServerUrl() + "/XRMServices/2011/OrganizationData.svc"; }

    // get entity with id
    this.retrieveOne = function (entity, id, callback) {
        if (jQuery) {
            var serviceUrl = this.getServiceUrl();
            var select = "/" + entity + "Set(guid'" + id + "')";

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: serviceUrl + select,
                beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
                success: function (data, textStatus, XmlHttpRequest) {
                    callback(data.d);
                },
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
                }
            });
        } else {
            alert('jQuery required!');
        }
    }

    // get entity(s) with query
    this.retrieveWithQuery = function (entity, query, callback) {
        if (jQuery) {
            var serviceUrl = this.getServiceUrl();
            var select = "/" + entity + "Set?" + query;

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: serviceUrl + select,
                beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
                success: function (data, textStatus, XmlHttpRequest) {
                    callback(data.d.results);
                },
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
                }
            });
        } else {
            alert('jQuery required!');
        }
    }

    //get formatted date
    this.getFormattedDate = function (date, format) {
        var d = new Date();
        d.setTime(date.getTime());

        var retVal = format
            .replace('yyyy', d.getFullYear())
            .replace('MM', (d.getMonth() < 9 ? '0' : '') + (d.getMonth() + 1))
            .replace('dd', (d.getDate() < 9 ? '0' : '') + d.getDate())
            .replace('HH', (d.getHours() < 9 ? '0' : '') + d.getHours())
            .replace('mm', (d.getMinutes() < 9 ? '0' : '') + d.getMinutes())
            .replace('ss', (d.getSeconds() < 9 ? '0' : '') + d.getSeconds());

        return retVal;
    }
}

// define $$ object of window
window.$$ = new arunesCrmJsLib();